import { Directive, ElementRef, Input, OnInit } from '@angular/core';
import { FormControl, NgForm, NgModel } from '@angular/forms';

import { CommonService } from '../../core/services/common.service';

declare const $: any;

/**
 * Decorates the form group with css class based on according form field.
 */
@Directive({ selector: '[opFormGroupValidationClass]' })
export class FormGroupValidationClassDirective implements OnInit {
    @Input() formModel: NgForm;
    @Input() fieldModel: FormControl | NgModel;
    jqueryElement = $(this.element.nativeElement);

    constructor(
        private commonService: CommonService,
        private element: ElementRef
    ) { }

    ngOnInit(): void {
        this.formModel.ngSubmit.subscribe((p: any): void => this.applyValidationClass());
        this.fieldModel.statusChanges.subscribe((p: any): void => this.applyValidationClass());
    }

    /**
     * Applies the css class for form field validation.
     */
    applyValidationClass(): void {
        if ((this.formModel.submitted || this.fieldModel.dirty) && this.fieldModel.valid) {
            this.jqueryElement.addClass('has-success');
        } else {
            this.jqueryElement.removeClass('has-success');
        }

        if ((this.formModel.submitted || this.fieldModel.dirty) && !this.fieldModel.valid) {
            this.jqueryElement.addClass('has-error');
        } else {
            this.jqueryElement.removeClass('has-error');
        }
    }
}